﻿/**
 * Twiget main script
 * @author muik
 */

var consumer = { 
	consumerKey   : "V77cDkU4wtH7vTXqJLVdg"
	, consumerSecret: "RcxkCwjhAdpc7GxeTizDOJLWtFThBUJL5Uc8BHJFc"
	, serviceProvider: {
		signatureMethod     : "HMAC-SHA1"
		, requestTokenURL     : "https://api.twitter.com/oauth/request_token"
		, userAuthorizationURL: "https://api.twitter.com/oauth/authorize"
		, accessTokenURL      : "https://api.twitter.com/oauth/access_token"
		, echoURL             : ""
		}
};

var timeline = {
	get_last_id: function() {
		if (this.items.length < 1) {
			return 0;
		}
		return this.items[this.items.length - 1].id;
	},
	items: []
};

var _resizingId = 0;
var _resizeTimer;
var _reqTimelineTimer;

String.prototype.bytes = function() {
    var l = 0;
    for (var i = 0; i < this.length; i++) {
        l += (this.charCodeAt(i) > 128) ? 2 : 1;
    }
    return l;
};

String.prototype.escapeHTML = function() {
	return this.replace(/&/g,'&amp;').replace(/</g,'&lt;').replace(/>/g,'&gt;');
}


function view_onOpen() {
	options.putDefaultValue('oauth_token', '');
	options.putDefaultValue('oauth_token_secret', '');
	options.putDefaultValue('user_id', '');
	options.putDefaultValue('screen_name', '');
	
	signinDiv.visible = false;
	timelineDiv.visible = false;
		
	var twitOauth = new TwitterOAuth();
	var onOpenSigninView = function() {
		//pincodeDiv.visible = false;		
		twitOauth.requestToken(function(res) {
			var url = consumer.serviceProvider.userAuthorizationURL + '?' + res;			
			signinLink.href = url;
			signinLink.onclick = function() {
				pincodeDiv.visible = true;
			};
			submitPincodeBtn.onclick = function() {
				twitOauth.requestAccessToken(pincodeEdit.value, function() {
					signinDiv.visible = false;
					timelineDiv.visible = true;
					requestHomeTimeline();
				});
			};
			pincodeEdit.value = '';
			timelineDiv.visible = false;
			signinDiv.visible = true;
		});
	};
	
	if (twitOauth.isAuthed()) {
		requestHomeTimeline();
		timelineDiv.visible = true;
	} else {
		onOpenSigninView();
	}
	
	pluginHelper.onAddCustomMenuItems = function(menu) {
		menu.AddItem('Sign out', twitOauth.isAuthed() ? 0: gddMenuItemFlagGrayed, function() {
			signOut();
			onOpenSigninView();
		});
	};
}

function signOut() {
	if (_reqTimelineTimer) {
		clearTimeout(_reqTimelineTimer);
	}
	
	options.putValue('oauth_token', '');
	options.putValue('oauth_token_secret', '');
	options.putValue('user_id', '');
	options.putValue('screen_name', '');
	
	while (timeline.items.length > 0) {
		var item =  timeline.items.shift();
		twitList.removeElement(twitList.children.item('msgDiv' + item.id));
	}
}

function requestHomeTimeline() {
	var action = 'http://api.twitter.com/1/statuses/home_timeline.json';
	var method = 'GET';
    var accessor = { consumerSecret: consumer.consumerSecret
                   , tokenSecret   : options.getValue('oauth_token_secret') };
	var message = { action: action
			  , method: method
			  , parameters: []
			  };
	var since_id = timeline.get_last_id();
	if (since_id) {
		message.action += '?since_id=' + since_id;
	}
	var requestBody = OAuth.formEncode(message.parameters);
	message.parameters.push(['oauth_consumer_key', consumer.consumerKey]);
	message.parameters.push(['oauth_signature_method', consumer.serviceProvider.signatureMethod]);
	message.parameters.push(['oauth_token', options.getValue('oauth_token')]);
	OAuth.completeRequest(message, accessor);
	var authorizationHeader = OAuth.getAuthorizationHeader("", message.parameters);	
	
	var req = new XMLHttpRequest();
	req.onreadystatechange = function() {
		if (req.readyState == 4) {
			if(req.status != 200) {
				//alert('error load timeline');
				return false;
			}
			
			updateTwitMessages(eval(req.responseText));
		}
	};

	req.open(message.method, message.action, true);
	req.setRequestHeader("Authorization", authorizationHeader);
	req.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
	req.send(requestBody);
	
	_reqTimelineTimer = setTimeout('requestHomeTimeline()', 60000 * 3);
}

function updateTwitMessages(res) {
	if (res.length < 1) {
		return;
	}
	for (var i = res.length - 1; i >= 0; i--) {
		var twit = res[i].retweeted_status ? res[i].retweeted_status : res[i];
		var item = twitList.appendElement('<div name="msgDiv' + res[i].id + '" width="100%" tooltip=""></div>');
		item.appendElement('<div name="border" x="3%" width="94%" height="1" background="#eeeeee" />');
		var lbl = item.appendElement('<label name="contentLbl" enabled="true" font="&FONT;" y="5" color="#333333"\
			height="100%" pinX="-38" valign="top" wordWrap="true" trimming="character-ellipsis" onmousewheel="onMouseWheel()">'
			+ res[i].text.replace(/\n/, ' ').escapeHTML() + '</label>');
		lbl.ondblclick = function(screen_name, id) {
			return function() {
				framework.openUrl('http://twitter.com/' + screen_name + '/statuses/' + id);
			};
		} (res[i].user.screen_name, res[i].id);
		var img = item.appendElement('<img name="profileImg" x="5" y="5" src="" enabled="true" onmousewheel="onMouseWheel()" />');
		img.ondblclick = function(screen_name) {
			return function() {
				framework.openUrl('http://twitter.com/' + screen_name);
			};
		} (res[i].user.screen_name);		
		
		if (res[i].retweeted_status) {
			var rt_img = item.appendElement('<img name="retwitter" x="23" y="30" width="15" height="15"\
				src="" enabled="true" onmousewheel="onMouseWheel()" />');
			try {
				fetchImage(rt_img, res[i].user.profile_image_url);
				fetchImage(img, res[i].retweeted_status.user.profile_image_url);
			} catch (e) {}
		} else {		
			try {
				fetchImage(img, res[i].user.profile_image_url);
			} catch (e) {}
		}
		
		var links = res[i].text.match(/https?:\/\/[^\.]+[^\s]+/gi);
		if (links) {
			for (var j = 0; j < links.length; j++) {
				item.appendElement('<a href="' + links[j] + '" size="8" x="5" y="' + (34 + 12 * j) + '" opacity="150"\
					font="arial">link' + (j + 1) + '</a>');
			}
		}
		
		timeline.items.push({
			id: res[i].id,
			links: links
		});
	}
	
	while (timeline.items.length > 50) {
		var item =  timeline.items.shift();
		twitList.removeElement(twitList.children.item('msgDiv' + item.id));
	}
	resizeContents();
}

function resizeContents() {
	_resizingId += 1;
	var id = _resizingId;
	
	var img_w = 30;
	var width = twitList.offsetWidth - img_w - 10;
	var size = 8;
	var listLen = twitList.children.count;
	twitList.height = 0;
	
	for (var i = timeline.items.length - 1; i >= 0; i--) {
		if (id < _resizingId) {
			return;
		}
		var item = timeline.items[i];
		var msg = twitList.children.item('msgDiv' + item.id);
		var img = msg.children.item('profileImg');
		var content = msg.children.item('contentLbl');
		var height = Math.ceil(content.innerText.bytes() * (size - 0.6) / width) * 10 + 10;
		if (height < 40) {
			height = 40;
		}
		if (item.links && height < 50) {
			height = 50;
		}
		
		msg.height = height;
		msg.y = twitList.height;
		content.size = size;
		content.width = width;
		img.width = img_w;
		img.height = img_w;
		
		
		twitList.height += height;
	}
	_resizingId = 0;
}

function onResize() {
	if (_resizeTimer) {
		clearTimeout(_resizeTimer);
	}
	_resizeTimer = setTimeout('resizeContents()', 500);
}

function fetchImage(img, url) {
	var req = new XMLHttpRequest();
	req.open('GET', encodeURI(url), true);
	req.onreadystatechange = function() {
		if (req.readyState == 4) {
			if(req.status == 200) {
				img.src = req.responseStream;
			} else {
				//alert('error down img');
			}
		}
	}
	req.send(null);
}

function onScroll() {
	twitList.y = -((twitList.height - timelineDiv.offsetHeight) * sb.value / sb.max);
}

function onMouseWheel() {
	sb.onchange = null;
	sb.value += (event.wheelDelta > 0 ? -5 : 5);
	onScroll();
}
